package gui;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * mylist.java
 *
 * Created on Oct 14, 2010, 8:34:39 PM
 */
 
import gui.TotalMainPanel.Positive;

import javax.swing.plaf.SliderUI;
import javax.swing.table.TableColumn;
import javax.swing.*;
import javax.swing.table.*;
import java.net.*;
import java.util.List;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.lang.Runtime;
import java.io.File;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

import util.i3enum.MessageBox;
import util.i3enum.MessageBoxIcon;
 
import dto.TotalFileBase;
import dto.TotalPartition;



import javax.swing.filechooser.FileSystemView;




/**
 *
 * @author ThaiBaoDoan
 */
public class MyList extends javax.swing.JPanel implements ActionListener {

    /** Creates new form mylist */
	 
	static int iFocus = 0;
	String iSelectItem;
	String NameFileSelect;
	private FileSystemView fsv = FileSystemView.getFileSystemView();

	public MyList() {
		initComponents();

	}

	public void InitDrive() {

	}
     
     
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        combobox_left = new javax.swing.JComboBox();
        combobox_left.setActionCommand("Act_Left_Combobox"); 
        combobox_right = new javax.swing.JComboBox();
        combobox_right.setActionCommand("Act_Right_Combobox");
        lbInfoPartion_left  =   new javax.swing.JLabel();
        lbInfoPartion_right =  new javax.swing.JLabel();
        splitPanel = new javax.swing.JSplitPane();
        panel_left = new javax.swing.JPanel();
        scrollbar_left = new javax.swing.JScrollPane();
        table_left = new javax.swing.JTable(){
            public boolean isCellEditable(int row, int column) {

                return false;
            }
        };
        panel_right = new javax.swing.JPanel();
        scrollbar_right = new javax.swing.JScrollPane();
        table_right = new javax.swing.JTable(){
            public boolean isCellEditable(int row, int column) {

                return false;
            }
        };
        combobox_left.setModel(new javax.swing.DefaultComboBoxModel(
        		dto.TotalPartition.GetAllPartitionIndex()
        		
        		)
        );
        combobox_right.setModel(new javax.swing.DefaultComboBoxModel(
        		dto.TotalPartition.GetAllPartitionIndex()
        		)
        );
        
        lbInfoPartion_left.setText("Left Information"); 
        lbInfoPartion_right.setText("Right Information"); 
        splitPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
        splitPanel.setDividerLocation(575);
        splitPanel.setDividerSize(10);

        
        table_left.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        table_left.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        table_left.setShowHorizontalLines(false);
        table_left.setShowVerticalLines(false); 
        table_left.getTableHeader().setReorderingAllowed(false);
         
        scrollbar_left.setViewportView(table_left);

       //Create Panel contain combobox & partition information
        JPanel panel_combobox_left = new JPanel(); 
        FlowLayout combox_left_layout = new FlowLayout();
        combox_left_layout.setAlignment(FlowLayout.LEFT);
        panel_combobox_left.setLayout(combox_left_layout); 
        panel_combobox_left.add(combobox_left);
        panel_combobox_left.add(lbInfoPartion_left);  
        //Test  Left panel - Begin
           table_left.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {

                },
                new String [] {
                    "Name", "Size", "Date Modified"
                }
            ) {
                Class[] types = new Class [] {
                    java.lang.Object.class, java.lang.String.class, java.lang.String.class
                };

                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }
            });
        table_left.getTableHeader().setResizingAllowed(true);
        javax.swing.GroupLayout panel_left_layout = new javax.swing.GroupLayout(panel_left);
        panel_left.setLayout(panel_left_layout);
        panel_left_layout.setHorizontalGroup(
            panel_left_layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel_left_layout.createSequentialGroup()
                .addGroup(panel_left_layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollbar_left, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE)
                    .addGroup(panel_left_layout.createSequentialGroup()
                        .addComponent(panel_combobox_left, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        ))
                .addContainerGap())
        );
        panel_left_layout.setVerticalGroup(
            panel_left_layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_left_layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panel_left_layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(panel_combobox_left, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    )
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(scrollbar_left, javax.swing.GroupLayout.PREFERRED_SIZE, 497, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        //Test - End
        splitPanel.setLeftComponent(panel_left);
        
        ////// RIGHT//////////////////
        table_right.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {

                },
                new String [] {
                    "Name", "Size", "Date Modified"
                }
            ) {
                Class[] types = new Class [] {
                    java.lang.Object.class, java.lang.String.class, java.lang.String.class
                };

                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }
            });
        table_right.getTableHeader().setResizingAllowed(true);
        table_right.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        table_right.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        table_right.setShowHorizontalLines(false);
        table_right.setShowVerticalLines(false);
        table_right.getTableHeader().setReorderingAllowed(false); 
        //Create Panel contain combobox & partition information
        JPanel panel_combobox_right = new JPanel(); 
        FlowLayout combox_right_layout = new FlowLayout();
        combox_right_layout.setAlignment(FlowLayout.LEFT);
        panel_combobox_right.setLayout(combox_right_layout); 
        panel_combobox_right.add(combobox_right);
        panel_combobox_right.add(lbInfoPartion_right);
      //Test  Left panel - Begin
        javax.swing.GroupLayout panel_right_layout = new javax.swing.GroupLayout(panel_right);
        panel_right.setLayout(panel_right_layout);
        panel_right_layout.setHorizontalGroup(
        		panel_right_layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel_right_layout.createSequentialGroup()
                .addGroup(panel_right_layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollbar_right, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE)
                    .addGroup(panel_right_layout.createSequentialGroup()
                        .addComponent(panel_combobox_right, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        ))
                .addContainerGap())
        );
        panel_right_layout.setVerticalGroup(
        		panel_right_layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_right_layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panel_right_layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(panel_combobox_right, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    )
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(scrollbar_right, javax.swing.GroupLayout.PREFERRED_SIZE, 497, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        table_left.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                LeftTableMouseClicked(evt);
            }
        });
        table_right.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                RightTableMouseClicked(evt);
            }
        });
        //Test - End
        
       
        scrollbar_right.setViewportView(table_right); 
        splitPanel.setRightComponent(panel_right);

         
        //My list Layout
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
        		 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                 .addComponent(splitPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 948, Short.MAX_VALUE
        ));
        layout.setVerticalGroup(
        	     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                 .addGroup(layout.createSequentialGroup()
                     .addComponent(splitPanel, javax.swing.GroupLayout.PREFERRED_SIZE,
                    		 536, javax.swing.GroupLayout.PREFERRED_SIZE))         
        );
    }// </editor-fold>
    public void SetLeftCombobox (String item)
    {
    	combobox_left.setActionCommand("left_temp");
    	combobox_left.setSelectedItem(item);
    	 combobox_left.setActionCommand("Act_Left_Combobox");
    }
    public void SetRightCombobox (String item)
    {
    	combobox_right.setActionCommand("right_temp");
    	combobox_right.setSelectedItem(item);
    	combobox_right.setActionCommand("Act_Right_Combobox");
    }
    public void SetListenAction(JFrame main)
    {
      if(combobox_left != null && combobox_right != null)
      {
    	  combobox_left.setActionCommand("Act_Left_Combobox");
    	  combobox_left.addActionListener((ActionListener)main);
    	  combobox_right.setActionCommand("Act_Right_Combobox");
    	  combobox_right.addActionListener((ActionListener)main);
      } 
    }
    public void Set_LeftCurrentList(List<TotalFileBase> listFile,String currentDir)
    {
    	leftlistFile = listFile;
    	setLeftCurrentDir(currentDir);
    	DefaultTableModel defaultLeftTable = (DefaultTableModel)table_left.getModel();
    	defaultLeftTable.getDataVector().removeAllElements();
    	defaultLeftTable.fireTableDataChanged();
    	int index = 0;
    	if(currentDir.length() >2)
    	{
    	  //If is a child folder add up button 
    	  JLabel up = new JLabel();
    	  up.setText("[..]");
    	  Icon upIcon =  new ImageIcon(util.general.total_Image.createImageIcon ("resources/images/up.png").getImage());
    	  up.setIcon(upIcon);
    	  table_left.getColumnModel().getColumn(0).setCellRenderer(new CustomTableCellRenderer(up));  
          defaultLeftTable.insertRow(index, new Object[]{new CustomTableCellRenderer(up),"" ,"" });
          index ++ ;
    	}
    	 for(int i = 0 ; i<listFile.size();i++)
         {
              JLabel temp = new JLabel();
              temp.setText(listFile.get(i).get_stdFileName());
              temp.setIcon(fsv.getSystemIcon(new File(currentDir + "\\" + listFile.get(i).get_stdFileName())));
              table_left.getColumnModel().getColumn(0).setCellRenderer(new CustomTableCellRenderer(temp));  
              defaultLeftTable.insertRow(i+index, new Object[] //If has up button : index from 1
             {
             new CustomTableCellRenderer(temp),listFile.get(i).get_lSize()!=-1 ? listFile.get(i).get_lSize(): "<Dir>" 
             ,listFile.get(i).get_stdLastModified()
             });
               
         }
    }
    public void Set_RightCurrentList(List<TotalFileBase> listFile,String currentDir)
    { 
    	rightlistFile = listFile;
    	setRightCurrentDir(currentDir);
    	DefaultTableModel defaultRightTable = (DefaultTableModel)table_right.getModel();
    	defaultRightTable.getDataVector().removeAllElements();
    	defaultRightTable.fireTableDataChanged();
    	int index = 0;
    	if(currentDir.length() >2)
    	{
    	  //If is a child folder add up button 
    	  JLabel up = new JLabel();
    	  up.setText("[..]");
    	  Icon upIcon =  new ImageIcon(util.general.total_Image.createImageIcon ("resources/images/up.png").getImage());
    	  up.setIcon(upIcon);
    	  table_right.getColumnModel().getColumn(0).setCellRenderer(new CustomTableCellRenderer(up));  
          defaultRightTable.insertRow(index, new Object[]{new CustomTableCellRenderer(up),"" ,"" });
          index ++ ;
    	}
    	 for(int i=0;i<listFile.size();i++)
         {
              JLabel temp = new JLabel();
              temp.setText(listFile.get(i).get_stdFileName());
              temp.setIcon(fsv.getSystemIcon(new File(currentDir + "\\" + listFile.get(i).get_stdFileName())));
              table_right.getColumnModel().getColumn(0).setCellRenderer(new CustomTableCellRenderer(temp));  
              defaultRightTable.insertRow(i+index, new Object[]
            		  {
            		  	new CustomTableCellRenderer(temp),listFile.get(i).get_lSize()!=-1 ? listFile.get(i).get_lSize(): "<Dir>" 
            		  	,listFile.get(i).get_stdLastModified()
            		  });
               
         }
    }
    //Left - Right Information
    public void SetDriveInformation(Positive Pos, TotalPartition Info)
    {
    	//Format
    	// [Label] [free size]'k' 'of' [total size] 'free'
    	
    	String label = String.format("[%s] %d k of %d k free", 
    			Info.get_stdFullName(),Info.get_lPartitionFreeSize(),Info.get_lPartitionSize());
    	if(Pos.equals(Positive.LEFT))
    	{
    		
    		lbInfoPartion_left.setText(label);
    	}
    	else if(Pos.equals(Positive.RIGHT))
    	{
    		lbInfoPartion_right.setText(label);
    	}
    	
    }
    
    //Event 
    public void LeftTableMouseClicked(java.awt.event.MouseEvent evt)
    {
    	int index = table_left.getSelectedRow();
    	if(index == 0 && getLeftCurrentDir().length() >2 )
    	{
    	  // Up button 
    		if (evt.getClickCount() == 2 && (evt.getButton() == MouseEvent.BUTTON1) )
    		{
    			String currentDir = getLeftCurrentDir().substring(0,getLeftCurrentDir().lastIndexOf("\\"));
    			 System.out.println(currentDir);
    			
    			List<TotalFileBase> temp = TotalFileBase.GetAllFile(currentDir+"\\");
    			Set_LeftCurrentList(temp,currentDir);
    			
    		}
    		return ; 
    	}
    	int index_list = (getLeftCurrentDir().length() == 2) ? index :(index- 1); 
    	TotalFileBase file = leftlistFile.get(index_list);
    	if(file.get_file().isDirectory())
    	{
    	   String currentDir = file.get_file().getAbsolutePath();
       	   List<TotalFileBase> temp = TotalFileBase.GetAllFile(currentDir);
       	   if(evt.getClickCount() == 1)
       	   {
       		  setCurrentFocus(FOCUS_LEFT_TABLE);
       	   }
       	   else	if (evt.getClickCount() == 2)
	    	{
	    		Set_LeftCurrentList(temp,currentDir);
	    	}
    	}
    	else
    	{
    		if (evt.getClickCount() == 2 && (evt.getButton() == MouseEvent.BUTTON1) )
	    	{
	    		//execute file
    			String URL = file.get_file().getAbsolutePath();
    			try{ 
                    String FullURL=new String("rundll32 SHELL32.DLL,ShellExec_RunDLL \""+URL+"\""); 
                    Runtime.getRuntime().exec(FullURL); 
                }
               catch(IOException ee)
               {
            	   MessageBoxDialog.Show("Can't not access " +URL,"Error",MessageBox.OK,MessageBoxIcon.ERROR);
               }

	    	}
    	}
    	
    	
    }
    
    public void RightTableMouseClicked(java.awt.event.MouseEvent evt)
    {
    	int index = table_right.getSelectedRow(); 
    	if(index == 0 && getRightCurrentDir().length() >2 )
    	{
    	  // Up button 
    		if (evt.getClickCount() == 2 && (evt.getButton() == MouseEvent.BUTTON1) )
    		{
    			String currentDir = getRightCurrentDir().substring(0,getRightCurrentDir().lastIndexOf("\\"));
    			 System.out.println("right: "+currentDir);
    			
    			List<TotalFileBase> temp = TotalFileBase.GetAllFile(currentDir+"\\");
    			Set_RightCurrentList(temp,currentDir);
    			
    		}
    		return ; 
    	}
    	int index_list = (getRightCurrentDir().length() == 2) ? index :(index- 1); 
    	TotalFileBase file = rightlistFile.get(index_list);
    	if(file.get_file().isDirectory())
    	{
    	   String currentDir = file.get_file().getAbsolutePath();
       	   List<TotalFileBase> temp = TotalFileBase.GetAllFile(currentDir);
       	  if(evt.getClickCount() == 1)
      	   {
      		   setCurrentFocus(FOCUS_RIGHT_TABLE);
      	   }
       	  else	if (evt.getClickCount() == 2)
	    	{
	    		Set_RightCurrentList(temp,currentDir);
	    	}
    	}
    	else
    	{
    		if (evt.getClickCount() == 2 && (evt.getButton() == MouseEvent.BUTTON1) )
	    	{
	    		//execute file
    			String URL = file.get_file().getAbsolutePath();
    			try{ 
                    String FullURL=new String("rundll32 SHELL32.DLL,ShellExec_RunDLL \""+URL+"\""); 
                    Runtime.getRuntime().exec(FullURL); 
                }
               catch(IOException ee)
               {
                 MessageBoxDialog.Show("Can't not access " +URL,"Error",MessageBox.OK,MessageBoxIcon.ERROR);
               }

	    	}
    	}
    	
    	
    }
    // Variables declaration - do not modify
    private javax.swing.JPanel panel_left;
    private javax.swing.JPanel panel_right;
    private javax.swing.JScrollPane scrollbar_left;
    private javax.swing.JScrollPane scrollbar_right;
    private javax.swing.JSplitPane splitPanel;
    public javax.swing.JTable table_left;
    private javax.swing.JTable table_right;
    private javax.swing.JComboBox combobox_left;
    private javax.swing.JComboBox combobox_right;
    private javax.swing.JLabel    lbInfoPartion_left;
    private javax.swing.JLabel    lbInfoPartion_right;
    List<TotalFileBase> leftlistFile;
    private String              leftCurrentDir;
    List<TotalFileBase> rightlistFile;
    private String              rightCurrentDir;
    public  static  final int FOCUS_LEFT_TABLE  = 1;
    public  static  final int FOCUS_RIGHT_TABLE  = 2;
    private int  nCurrentFocus = 0; // 
    // End of variables declaration
    
	@Override
	public void actionPerformed(ActionEvent event) {
		// TODO Auto-generated method stub
		 
	}

	public int getCurrentFocus() {
		return nCurrentFocus;
	}

	public void setCurrentFocus(int nCurrentFocus) {
		this.nCurrentFocus = nCurrentFocus;
	}

	String getLeftCurrentDir() {
		return leftCurrentDir;
	}

	void setLeftCurrentDir(String leftCurrentDir) {
		this.leftCurrentDir = leftCurrentDir;
	}

	String getRightCurrentDir() {
		return rightCurrentDir;
	}

	void setRightCurrentDir(String rightCurrentDir) {
		this.rightCurrentDir = rightCurrentDir;
	}

}
